#include "globalhotkey.h"
#include <QCoreApplication>
#include <QDebug>

#if defined(Q_OS_WIN)
#  define WIN32_LEAN_AND_MEAN
#  include <windows.h>
#endif

GlobalHotkeyManager::GlobalHotkeyManager(QObject* parent)
    : QObject(parent) {
    // 安装原生事件过滤器
    qApp->installNativeEventFilter(this);
}

GlobalHotkeyManager::~GlobalHotkeyManager() {
    unregisterAll();
    qApp->removeNativeEventFilter(this);
}

bool GlobalHotkeyManager::registerScreenshotHotkey() {
#if defined(Q_OS_WIN)
    if (m_registeredScreenshot) return true;
    // Ctrl + Alt + S 作为截图热键
    UINT fsModifiers = MOD_CONTROL | MOD_ALT;
    UINT vk = 0x53; // 'S'
    if (RegisterHotKey(nullptr, m_screenshotId, fsModifiers, vk)) {
        m_registeredScreenshot = true;
        return true;
    } else {
        qWarning() << "RegisterHotKey failed with error" << GetLastError();
        return false;
    }
#else
    // 非 Windows 平台暂不实现
    qWarning() << "Global hotkey not implemented on this platform.";
    return false;
#endif
}

bool GlobalHotkeyManager::registerGhostModeHotkey() {
#if defined(Q_OS_WIN)
    if (m_registeredGhost) return true;
    // Alt + Shift + L 作为幽灵模式热键
    UINT fs = MOD_ALT | MOD_SHIFT;
    UINT vk = 0x4C; // 'L'
    if (RegisterHotKey(nullptr, m_ghostId, fs, vk)) { m_registeredGhost = true; return true; }
    qWarning() << "RegisterHotKey(ghost) failed with error" << GetLastError();
    return false;
#endif
    return false;
}

void GlobalHotkeyManager::unregisterAll() {
#if defined(Q_OS_WIN)
    if (m_registeredScreenshot) { UnregisterHotKey(nullptr, m_screenshotId); m_registeredScreenshot = false; }
    if (m_registeredGhost) { UnregisterHotKey(nullptr, m_ghostId); m_registeredGhost = false; }
#endif
}

bool GlobalHotkeyManager::nativeEventFilter(const QByteArray& eventType, void* message, qintptr* result) {
    Q_UNUSED(result);
#if defined(Q_OS_WIN)
    // 处理 WM_HOTKEY
    if (eventType == "windows_generic_MSG" || eventType == "windows_dispatcher_MSG") {
        MSG* msg = static_cast<MSG*>(message);
        if (msg && msg->message == WM_HOTKEY) {
            int id = static_cast<int>(msg->wParam);
            if (id == m_screenshotId) { emit screenshotHotkeyPressed(); return false; }
            if (id == m_ghostId) { emit ghostModeHotkeyPressed(); return false; }
        }
    }
#endif
    return false;
}
